package ncov.web;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ncov.model.*;
import ncov.service.GradeService;
import ncov.service.ReportRecordService;
import ncov.service.StudentService;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WuChangJian
 * @date 2020/5/31 8:53
 */
@PropertySource("classpath:global.properties")
public class ReportRecordAction extends ActionSupport implements ModelDriven<ReportRecord> {

    private Logger logger = Logger.getLogger(ReportRecordAction.class);
    private static final String FORWARD = "FORWARD";
    private static final String STREAM = "stream";

    private ReportRecord reportRecord = new ReportRecord();
    @Value("${path}")
    private String exportPath;
    // 结果的封装
    private Result result;
    private InputStream inputStream;
    private String excelFileName;
    // 分页查询条件
    private Integer currentGradeId; // 当前班级ID
    private Integer currentPage;          // 起始页码
    private Integer submitted;      // 上报情况：-1 所有 0 上报 1 未上报
    private Integer count;          // 页面容量

    @Autowired
    private ReportRecordService reportRecordService;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private StudentService studentService;

    /**
     * 初始化登记表信息（前台）
     * 实际要获取用户信息，这里交给了用户模块
     * 只是起了中间路由的作用
     * @return
     */
    public String initReportRecords() {
        return FORWARD;
    }

    /**
     * 登记表单信息（前台）
     * 当学生登录以后，前台需要设置一个隐藏表单域，用于存放stuId
     * 新增或更新report_record记录
     * @return
     */
    public String postReportRecords() {
        result = new Result();
        ReportRecord reportRecord = reportRecordService.reportRecord(this.reportRecord);
        if (reportRecord != null) {
            result.setSuccess(true);
            result.setData(reportRecord);
        } else {
            result.setSuccess(false);
            result.setErrMsg("内部系统错误");
        }
        return SUCCESS;
    }

    /**
     * 获取登记信息表（前台）
     * @return
     */
    public String getReportRecords() {
        Map<String, Object> modelMap = new HashMap<>();
        result = new Result();
        ReportRecord reportRecord = reportRecordService.reportRecord(this.reportRecord);
        if (reportRecord != null) {
            result.setSuccess(true);
            modelMap.put("reportRecords", reportRecord);
            result.setData(modelMap);
        } else {
            result.setSuccess(false);
            result.setErrMsg("内部系统错误");
        }
        return SUCCESS;
    }

    /**
     * 初始化后台首页信息
     * @return
     */
    public String initEndReportRecords() {
        Map<String, Object> modelMap = new HashMap<>();
        HttpSession session = ServletActionContext.getRequest().getSession();
        LocalAuth localAuth = (LocalAuth) session.getAttribute("localAuth");
        Staff staff = localAuth.getStaff();
        if (staff != null) {
            Department deptReportRecords = reportRecordService.getDeptReportRecords(staff.getDeptId());
            result = new Result();
            modelMap.put("department", deptReportRecords);
            modelMap.put("staff", staff);
            modelMap.put("abnormalCount", reportRecordService.calcAbnormal(deptReportRecords.getDeptName()));
            result.setData(modelMap);
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
            result.setErrMsg("未获取到职工信息！");
        }
        return SUCCESS;
    }

    /**
     * 分页查询
     * @return
     */
    public String pageSelect() {
        Map<String, Object> modelMap = new HashMap<>();
        HttpSession session = ServletActionContext.getRequest().getSession();
        LocalAuth localAuth = (LocalAuth) session.getAttribute("localAuth");
        Staff staff = localAuth.getStaff();
        List<Student> studentInClass = null;
        // int total;// 当前查询条件下的总记录数 不需要设置，班级的总人数就是总记录数
        result = new Result();
        if (staff != null) {
            if (currentGradeId == null) {
                List<Grade> grades = gradeService.getGradesByStaffId(staff.getStaffId());
                if (grades != null && grades.size() > 0) {
                    // 对参数封装一层
                    PageModel pageModel = new PageModel(grades.get(0).getGradeId(), currentPage - 1, count, submitted, null);
                    studentInClass = studentService.selectPage(pageModel);
                    modelMap.put("grades", grades);
                    modelMap.put("reports", studentInClass);
                }
            } else {
                currentPage = (currentPage - 1) * count;
                PageModel pageModel = new PageModel(currentGradeId, currentPage, count, submitted, null);
                studentInClass = studentService.selectPage(pageModel);
                modelMap.put("reports", studentInClass);
            }
            result.setSuccess(true);
            result.setData(modelMap);
        }
        return SUCCESS;
    }
    /**
     * 导出登记信息表
     * @return
     */
    public String outReportRecords() throws FileNotFoundException, UnsupportedEncodingException {
        Grade grade = gradeService.getGrade(currentGradeId);
        if (grade != null) {
            File file = reportRecordService.exportRecords(grade.getGradeId(), exportPath);
            if (file != null) {
                logger.info("导出文件为："+file.getName());
                this.excelFileName = new String(file.getName().getBytes(), "ISO8859-1");
                this.inputStream = new FileInputStream(file);
            }
            else {
                logger.info("班级ID->" + currentGradeId + "下没有登记信息记录！");
            }
        }
        return STREAM;
    }

    public ReportRecord getReportRecord() {
        return reportRecord;
    }

    public void setReportRecord(ReportRecord reportRecord) {
        this.reportRecord = reportRecord;
    }
    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }
    @Override
    public ReportRecord getModel() {
        return reportRecord;
    }

    public Integer getCurrentGradeId() {
        return currentGradeId;
    }

    public void setCurrentGradeId(Integer currentGradeId) {
        this.currentGradeId = currentGradeId;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getSubmitted() {
        return submitted;
    }

    public void setSubmitted(Integer submitted) {
        this.submitted = submitted;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public String getExportPath() {
        return exportPath;
    }

    public void setExportPath(String exportPath) {
        this.exportPath = exportPath;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getExcelFileName() {
        return excelFileName;
    }

    public void setExcelFileName(String excelFileName) {
        this.excelFileName = excelFileName;
    }
}
